package controller

import (
	"gin/response"
	"gin/service"
	"gin/types"
	"github.com/gin-gonic/gin"
)

var (
	taskService         service.Task
	statusService       service.Status
	TaskMyResponsible   service.TaskMyResponsible
	taskDelayService    service.TaskDelay
	taskAbnormalService service.TaskAbnormal
)

type Task struct {
}

// ManHourRankReq 获取进行中的项目列表请求参数
type ManHourRankReq struct {
	Limit    *int  `json:"limit"`
	TenantId int64 `json:"tenant_id" binding:"required"`
}

// StatisticsReq 任务统计请求参数
type StatisticsReq struct {
	TenantId int64 `json:"tenant_id" binding:"required"`
}

// VersionTrendReq 审核记录请求参数
type VersionTrendReq struct {
	Days uint64 `json:"days" binding:"required"`
}

// StepCategoryStatisticsReq 任务分类统计请求参数
type StepCategoryStatisticsReq struct {
	TenantId int64 `json:"tenant_id" binding:"required"`
}

// CountVersionReq 统计版本数量请求参数
type CountVersionReq struct {
	TenantId  int64  `json:"tenant_id" binding:"required"`
	ProjectId uint64 `json:"project_id"`
	StartTime uint64 `json:"start_time" binding:"required"`
	EndTime   uint64 `json:"end_time" binding:"required"`
}

// FinanceStatisticsReq 基于任务的财务数据统计请求参数
type FinanceStatisticsReq struct {
	TenantId        int64    `json:"tenant_id" binding:"required"`
	ProjectIds      []uint64 `json:"project_ids"`
	EpisodesIds     []uint64 `json:"episodes_ids"`
	PlanEndTimeFrom uint64   `json:"plan_end_time_from"`
	PlanEndTimeTo   uint64   `json:"plan_end_time_to"`
}

// RequiresStatisticsReq 获取指定时间段任务待审核数量和待交付总数
type RequiresStatisticsReq struct {
	TenantId        int64    `json:"tenant_id" binding:"required"`
	ProjectIds      []uint64 `json:"project_ids" binding:"required"`
	PlanEndTimeFrom uint64   `json:"plan_end_time_from"`
	PlanEndTimeTo   uint64   `json:"plan_end_time_to"`
}

// CountRealTimeTaskReq 统计实时任务情况过滤参数
type CountRealTimeTaskReq struct {
	TenantId   int64    `json:"tenant_id" binding:"required"`
	ProjectIds []uint64 `json:"project_ids"`
}

// WorkRank 获取进行中的项目列表
func (c *Task) WorkRank(ctx *gin.Context) {

	var req ManHourRankReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	limit := 100
	if req.Limit != nil {
		limit = *req.Limit
	}

	resData, queryErr := taskService.WorkRank(req.TenantId, limit)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// Statistics 任务统计
func (c *Task) Statistics(ctx *gin.Context) {
	var req StatisticsReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	// 调用statusService查询状态分组状态id列表
	statusCorrespondData, err := statusService.GetStatusIdGroupByCorrespond()
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	resData, queryErr := taskService.Statistics(statusCorrespondData, req.TenantId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

func (c *Task) VersionTrend(ctx *gin.Context) {
	var req VersionTrendReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, queryErr := taskService.VersionSubmitTrend(req.Days)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// StepCategoryStatistics 分类任务数量统计
func (c *Task) StepCategoryStatistics(ctx *gin.Context) {
	var req StepCategoryStatisticsReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, queryErr := taskService.StepCategoryStatistics(req.TenantId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// CountVersionByDepartment 统计工序分类的某个时间段的版本提交次数
func (c *Task) CountVersionByDepartment(ctx *gin.Context) {
	var req CountVersionReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, queryErr := taskService.CountDepartmentVersionByStepCategory(req.TenantId, req.StartTime, req.EndTime, req.ProjectId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// FinanceStatistics 基于任务工时数据的财务分析
func (c *Task) FinanceStatistics(ctx *gin.Context) {
	var req FinanceStatisticsReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, queryErr := taskService.FinanceStatistics(req.TenantId, req.ProjectIds, req.EpisodesIds, req.PlanEndTimeFrom, req.PlanEndTimeTo)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// RequiresStatistics 获取指定时间段任务待审核数量和待交付总数
func (c *Task) RequiresStatistics(ctx *gin.Context) {
	var req RequiresStatisticsReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, queryErr := taskService.RequiresStatistics(req.TenantId, req.ProjectIds, req.PlanEndTimeFrom, req.PlanEndTimeTo)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// CountUnfinishedTaskWorkOrder 统计未完成工单数量，不需要限制时间，只要是未完成的一直显示
func (c *Task) CountUnfinishedTaskWorkOrder(ctx *gin.Context) {
	var req CountRealTimeTaskReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, queryErr := taskService.CountUnfinishedTaskWorkOrder(req.TenantId, req.ProjectIds)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"number": resData}, "success")
	}
}

// CountCompletedTask 统计指定租户和项目已完成任务数量，不需要限制时间
func (c *Task) CountCompletedTask(ctx *gin.Context) {
	var req CountRealTimeTaskReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	// 获取完成状态列表
	corresponds := []string{"done"}
	ipStatusIds, _ := statusService.GetStatusIdsByCorrespond(corresponds)

	resData, queryErr := taskService.CountTaskByStatus(req.TenantId, req.ProjectIds, ipStatusIds)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"number": resData}, "success")
	}
}

// CountInProgressTask 统计指定租户和项目进行中任务数量
func (c *Task) CountInProgressTask(ctx *gin.Context) {
	var req CountRealTimeTaskReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	// 获取未完成状态列表
	corresponds := []string{"feedback", "daily", "in_progress"}
	ipStatusIds, _ := statusService.GetStatusIdsByCorrespond(corresponds)

	resData, queryErr := taskService.CountTaskByStatus(req.TenantId, req.ProjectIds, ipStatusIds)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"number": resData}, "success")
	}
}

// CountUnfinishedAndOverdueTask 统计指定租户和项目逾期任务数量
func (c *Task) CountUnfinishedAndOverdueTask(ctx *gin.Context) {
	var req CountRealTimeTaskReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	// 获取未完成状态列表
	corresponds := []string{"feedback", "daily", "in_progress"}
	ipStatusIds, _ := statusService.GetStatusIdsByCorrespond(corresponds)

	resData, queryErr := taskService.CountUnfinishedAndOverdueTask(req.TenantId, req.ProjectIds, ipStatusIds)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"number": resData}, "success")
	}
}

// GetTaskWorkloadStatistics 获取团队总产能负载数据
func (c *Task) GetTaskWorkloadStatistics(ctx *gin.Context) {
	var req CountRealTimeTaskReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, queryErr := taskService.GetTaskWorkloadStatistics(req.TenantId, req.ProjectIds)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// GetWaitAssignStepCategoryCount 任务待分配分类统计
func (c *Task) GetWaitAssignStepCategoryCount(ctx *gin.Context) {
	var req types.GetWaitAssignStepCategoryCountReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, queryErr := taskService.GetWaitAssignStepCategoryCount(req)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// MyResponsibleTaskList 我负责的任务
func (c *Task) MyResponsibleTaskList(ctx *gin.Context) {
	var req types.GetListReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	tenantId := service.GetInt64FromContext(ctx, "tenant_id")
	resData, queryErr := TaskMyResponsible.GetList(ctx, req, tenantId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// UserList 用户列表
func (c *Task) UserList(ctx *gin.Context) {
	var req types.GetListReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	tenantId := service.GetInt64FromContext(ctx, "tenant_id")
	resData, queryErr := TaskMyResponsible.UserList(req, tenantId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// MyResponsibleTaskCount 我负责的任务
func (c *Task) MyResponsibleTaskCount(ctx *gin.Context) {
	var req types.GetListReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	//tenantId := service.GetInt64FromContext(ctx, "tenant_id")
	resData, queryErr := TaskMyResponsible.GetCount(ctx, req)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// Count 任务统计
func (c *Task) Count(ctx *gin.Context) {
	var req types.TaskCountReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	tenantId := service.GetInt64FromContext(ctx, "tenant_id")

	resData, queryErr := TaskMyResponsible.Count(ctx, req, tenantId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// TodoTaskOverview 任务待办概览
func (c *Task) TodoTaskOverview(ctx *gin.Context) {
	var req types.TodoTaskOverviewReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	userId := service.GetInt64FromContext(ctx, "user_id")
	tenantUserId := service.GetInt64FromContext(ctx, "tenant_id")
	resData, queryErr := taskService.TodoTaskOverview(req, userId, tenantUserId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// CheckShotTaskDone 检查镜头任务的完成情况
func (c *Task) CheckShotTaskDone(ctx *gin.Context) {

	var req types.TaskCheckShotTaskDoneReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	// 获取当前租户所有是组员和组长的角色
	resData, queryErr := taskService.CheckShotTaskDone(req.ProjectId, req.EpisodeId, req.ScList, req.SeqList)

	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}

}

// TaskSurvey 生产统计报表
func (c *Task) TaskSurvey(ctx *gin.Context) {
	var req types.TaskSurveyReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	tenantId := service.GetInt64FromContext(ctx, "tenant_id")

	var resData interface{}
	var queryErr error
	if req.QueryType == "department" {
		resData, queryErr = taskService.TaskSurveyByDepartment(tenantId, req.ProjectId, req.StartTime, req.EndTime, req.EpisodeList, req.DepartmentIdList, req.StepCategoryIdList, req.StepIdList)
	} else {
		resData, queryErr = taskService.TaskSurveyByStepCategory(tenantId, req.ProjectId, req.StartTime, req.EndTime, req.EpisodeList, req.DepartmentIdList, req.StepCategoryIdList, req.StepIdList)
	}

	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// TaskSurveyDetailList 生产统计报表详情
func (c *Task) TaskSurveyDetailList(ctx *gin.Context) {
	var req types.TaskSurveyDetailListReq
	err := ctx.ShouldBindJSON(&req)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	tenantId := service.GetInt64FromContext(ctx, "tenant_id")
	resData, queryErr := taskService.TaskSurveyDetailList(tenantId, req.Id, req.ParentId, req.ColumnKey, req.Type, req.Page, req.ProjectId, req.StartTime, req.EndTime, req.EpisodeList)

	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// TaskCompletion 任务完成情况
func (c *Task) TaskCompletion(ctx *gin.Context) {
	var req types.TaskCompletionReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	userId := service.GetInt64FromContext(ctx, "user_id")
	tenantUserId := service.GetInt64FromContext(ctx, "tenant_id")
	resData, queryErr := taskService.TaskCompletion(req, userId, tenantUserId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// WorkOrderSituation 工单情况
func (c *Task) WorkOrderSituation(ctx *gin.Context) {

	var req types.WorkOrderTaskCompletionReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	tenantUserId := service.GetInt64FromContext(ctx, "tenant_id")
	resData, queryErr := taskService.WorkOrderSituation(req, tenantUserId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// TaskCompletionList 任务完成情况列表
func (c *Task) TaskCompletionList(ctx *gin.Context) {

	var req types.TaskCompletionListReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	tenantUserId := service.GetInt64FromContext(ctx, "tenant_id")
	resData, queryErr := taskService.TaskCompletionList(req, tenantUserId)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// UserCountDetail 用户统计详情
func (c *Task) UserCountDetail(ctx *gin.Context) {

	var req types.UserCountDetailReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	resData, queryErr := taskService.UserCountDetail(ctx, req)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// DelayCount 任务统计
func (c *Task) DelayCount(ctx *gin.Context) {
	var req types.DelayCountReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}
	resData, queryErr := taskDelayService.Count(req)
	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}
